package com.epro.dx.activity.order;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.order.fragment.ShippingTrackingFragment;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.widget.PagerSlidingTabStrip;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.Package;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * @author Tony 含有多个包裹时的物流信息页面
 */
public class ShippingTrackingActivity extends BaseFragmentActivity {

    private static final String TAG = "ShippingTrackingActivity";
    private TextView orderNumber;
    private RelativeLayout orderNumberContain;
    private PagerSlidingTabStrip trackingTab;
    private ViewPager viewPager;
    private RelativeLayout backBt;// 返回按钮
    private String orderNumber2;
    private ArrayList<Package> mPackages = new ArrayList<Package>();// 获取到的物流信息
    private String currencyCode;
    private VpAdapter vpAdapter;
    private Tracker tracker;
    private Button copyBtn;
    // 复制板
    private ClipboardManager clipBoardManager;
    private boolean fromOrderTrackPage;
    private boolean fromJG;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_shippingtracking);
        tracker = DXApplication.getContext()
                .getTracker(TrackerName.APP_TRACKER);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onResume() {
        // GA跟踪
        tracker.setScreenName("ShippingInfo");
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        super.onResume();
    }

    /**
     * 加载事件监听
     */
    @SuppressLint("NewApi")
    private void initEvent() {

        backBt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                //如果是从极光推送跳转过来的，则返回的时候跳转到主界面
                if (fromJG) {
                    startActivity(new Intent(ShippingTrackingActivity.this, HomeActivity.class));
                }
                // 返回上一个页面
                finish();
            }
        });
        // 错误页面重试按钮
        retryBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncTaskUtil.executeTask(new GetShippingInfo());
            }
        });

        copyBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ClipData myClip = ClipData.newPlainText("text", orderNumber2);
                clipBoardManager.setPrimaryClip(myClip);
                showToast(getString(R.string.copy_success));
            }
        });
    }

    /**
     * 加载初始数据
     */
    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            orderNumber2 = intent.getStringExtra("OrderNumber");
            currencyCode = intent.getStringExtra("CurrencyCode");
            fromOrderTrackPage = intent.getBooleanExtra("fromOrderTrackPage", false);
            fromJG = intent.getBooleanExtra("fromJG", false);

        }
        if (!TextUtils.isEmpty(orderNumber2)) {
            orderNumber.setText(orderNumber2);
        }

        vpAdapter = new VpAdapter(getSupportFragmentManager());
        viewPager.setAdapter(vpAdapter);
        trackingTab.setViewPager(viewPager);
        trackingTab.setTextColor(
                getResources().getColor(R.color.myorder_tab_text_normal),
                getResources().getColor(R.color.myorder_tab_text_selected));

        // 调用接口加载数据
        AsyncTaskUtil.executeTask(new GetShippingInfo());
    }

    /**
     * 加载视图
     */
    private void initView() {
        clipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        copyBtn = (Button) findViewById(R.id.copy_order_number);
        // 订单号
        orderNumber = (TextView) findViewById(R.id.shipping_tracking_order_number);
        orderNumberContain = (RelativeLayout) findViewById(R.id.shipping_tracking_order_number_contain);
        // Tab
        trackingTab = (PagerSlidingTabStrip) findViewById(R.id.shipping_tracking_tab);
        viewPager = (ViewPager) findViewById(R.id.shipping_tracking_viewpager);
        backBt = (RelativeLayout) findViewById(R.id.topbar_back);
    }

    /**
     * @author Tony viewpager数据适配器
     */
    class VpAdapter extends FragmentStatePagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
        }

        @Override
        public Fragment getItem(int position) {
            // TODO Auto-generated method stub
            Package pack = mPackages.get(position);
            ShippingTrackingFragment shippingTrackingFragment = new ShippingTrackingFragment(
                    pack, currencyCode);
            return shippingTrackingFragment;
        }

        @Override
        public int getCount() {
            if (mPackages != null && mPackages.size() > 0) {
                return mPackages.size();
            }
            return 0;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return getString(R.string.shippingTracking_package) + " "
                    + (position + 1);
        }

    }

    /**
     * @author tony 获取物流信息
     */
    class GetShippingInfo extends BaseNeedReLoginTask {

        private ArrayList<Package> packages;

        @Override
        protected void onPreExecute() {
            showLoadingLayout(viewPager);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                packages = ProviderFactory.createOrderServiceProvider()
                        .GetShippingInfo(orderNumber2, null,
                                ActivityUtil.getCustomerToken(),
                                ActivityUtil.getCustomerID());
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            hideAllLayout(viewPager);
            if (!isFinishing()) {
                if ("0".equals(result)) {
                    trackingTab.setVisibility(View.VISIBLE);
                    orderNumberContain.setVisibility(View.VISIBLE);
                    mPackages.clear();
                    if (packages != null && packages.size() > 0) {
                        mPackages.addAll(packages);
                    }

                    //如果是从物流列表跳转过来的，因为是没有带货币好过来的，所以这里就设置货币号,其他页面过来则不影响
                    if (fromOrderTrackPage | fromJG) {
                        currencyCode = StringUtil.getConfig("CurrencyCodeStr", "");
                    }

                    setData();
                } else if (!isRelogin) {
                    trackingTab.setVisibility(View.GONE);
                    orderNumberContain.setVisibility(View.GONE);
                    if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE
                            .equals(result)) {
                        showErrorLayout(viewPager, R.string.internet_error,
                                R.string.internet_suggest,
                                R.drawable.no_internet);
                    } else {
                        showErrorLayout(viewPager, R.string.server_busy,
                                R.string.server_suggest, R.drawable.no_internet);
                    }
                }
            }
        }

        @Override
        protected Context setContext() {
            return ShippingTrackingActivity.this;
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new GetShippingInfo();
        }

    }

    /**
     * 设置页面数据显示
     */
    public void setData() {
        if (mPackages != null && mPackages.size() > 0) {
            vpAdapter.notifyDataSetChanged();
            trackingTab.notifyDataSetChanged();
//			vpAdapter = new VpAdapter(getSupportFragmentManager());
//			viewPager.setAdapter(vpAdapter);
//			trackingTab.setViewPager(viewPager);
//			trackingTab.setTextColor(
//					getResources().getColor(R.color.myorder_tab_text_normal),
//					getResources().getColor(R.color.myorder_tab_text_selected));
        } else {
            // 返回数据为空时，订单有问题，暂时显示为服务端异常页面
            trackingTab.setVisibility(View.GONE);
            orderNumberContain.setVisibility(View.GONE);
            showErrorLayout(viewPager, R.string.server_busy,
                    R.string.server_suggest, R.drawable.no_internet);
        }
        trackingTab.setTextSize(getResources().getDimensionPixelSize(
                R.dimen.text_size_14));
    }

    //如果是从极光推送跳转过来的，则返回的时候跳转到主界面
    @Override
    public void onBackPressed() {
        if (fromJG) {
            startActivity(new Intent(this, HomeActivity.class));
            finish();
        }
    }
}
